package com.ashlikun.keeplive

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.app.Service
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Process
import android.util.Log
import androidx.activity.ComponentActivity
import com.ashlikun.keeplive.config.ForegroundNotification
import com.ashlikun.keeplive.config.KeepLiveConfig
import com.ashlikun.keeplive.config.KeepNotificationUtils
import com.ashlikun.keeplive.service.JobHandlerService
import com.ashlikun.keeplive.service.LocalService
import com.ashlikun.keeplive.service.RemoteService
import java.util.Locale


/**
 * 保活工具
 */
typealias KeepLiveCall = (service: Service) -> Unit

object KeepLive {
    var RECEIVER_KEEP_STOP = "_KEEP_STOP"
        private set
    var NOTIFY_TYPE = "KEEP_NOTIFY_TYPE"
        private set
    lateinit var app: Application

    //保活是否运行
    var isStart = false

    //通知id
    var notificationId = 13691

    //JobScheduler 的id
    var jobId = 121

    /**
     * 运行中
     * 由于服务可能会多次自动启动，该方法可能重复调用
     */
    var onWorkingCall: KeepLiveCall? = null

    /**
     * 服务终止
     * 由于服务可能会被多次终止，该方法可能重复调用，需同onWorking配套使用，如注册和注销
     */
    var onStopCall: KeepLiveCall? = null

    val config = KeepLiveConfig()

    /**
     * 在Application 初始化
     */
    fun init(
        app: Application,
        notifyClickIntent: Intent,
        isDebug: Boolean? = null,
        remoteEnable: Boolean? = null,
        isCheckStart: Boolean? = null,
        jobServiceEnable: Boolean? = null,
        alarmManagerInterval: Long? = null,
    ) {
        this.app = app
        RECEIVER_KEEP_STOP = app.packageName + RECEIVER_KEEP_STOP
        NOTIFY_TYPE = app.packageName + NOTIFY_TYPE
        config.notifyClickIntent = notifyClickIntent
        if (isDebug != null) config.isDebug = isDebug
        if (remoteEnable != null) config.remoteEnable = remoteEnable
        if (isCheckStart != null) config.isCheckStart = isCheckStart
        if (jobServiceEnable != null) config.jobServiceEnable = jobServiceEnable
        if (alarmManagerInterval != null) config.alarmManagerInterval = alarmManagerInterval
    }

    /**
     * 创建foregroundNotification 对应的通知栏Builder
     * 前提foregroundNotification 不为null
     */
    fun createNot(context: Context) = if (config.foregroundNotification == null) null else KeepNotificationUtils.createNotification(
        context, config.foregroundNotification!!.title, config.foregroundNotification!!.description, config.foregroundNotification!!.iconRes, config.notifyClickIntent!!
    )

    /**
     * 启动保活
     * 1:先检查是否可以关闭电池优化
     * 2：未关闭就使用备选的方案，一像素，守护进程，无声音乐
     * 3：启动后要在结束的地方调用 stopWork 方法
     */
    fun startIgnoreBattery(activity: ComponentActivity, foregroundNotification: ForegroundNotification) {
        activity.ignoreBattery {
            startWork(foregroundNotification)
        }
    }

    /**
     * 启动保活
     * 未打开电池优化或者自启动的使用这个方法
     *
     * @param foregroundNotification 前台服务 必须要，安卓8.0后必须有前台通知才能正常启动Service
     */
    fun startWork(foregroundNotification: ForegroundNotification) {
        if (isMainProcess()) {
            loge("KeepLive startWork")
            isStart = true
            config.foregroundNotification = foregroundNotification
            startService()
            if (config.alarmManagerInterval >= 0) {
                AlarmManageHelp.get().interval = config.alarmManagerInterval
                AlarmManageHelp.get().startAlarmManager()
            }
        }
    }

    /**
     * 启动内部服务
     */
    internal fun startService() {
        isStart = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && config.jobServiceEnable) {
            //启动定时器，在定时器中启动本地服务和守护进程
            val intent = Intent(app, JobHandlerService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                app.startForegroundService(intent)
            } else {
                app.startService(intent)
            }
        } else {
            //启动本地服务
            app.startService(Intent(app, LocalService::class.java))
            if (config.remoteEnable) {
                //启动守护进程
                app.startService(Intent(app, RemoteService::class.java))
            }
        }
    }


    /**
     * 停止保活
     *
     * @param application            your application
     * @param foregroundNotification 前台服务 必须要，安卓8.0后必须有前台通知才能正常启动Service
     * @param keepLiveService        保活业务
     */
    fun stopWork() {
        if (isMainProcess()) {
            isStart = false
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && config.jobServiceEnable) {
                //关闭定时器，在定时器中启动本地服务和守护进程
                val intent = Intent(app, JobHandlerService::class.java)
                app.stopService(intent)
            } else {
                //关闭本地服务
                app.stopService(Intent(app, LocalService::class.java))
                if (config.remoteEnable) {
                    //启动守护进程
                    app.stopService(Intent(app, RemoteService::class.java))
                }
            }
            //发送退出广播
            app.sendBroadcast(Intent(RECEIVER_KEEP_STOP))
        }
    }

    fun isMainProcess(): Boolean {
        val pid = Process.myPid()
        var processName = ""
        val mActivityManager = app.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningAppProcessInfos = mActivityManager.runningAppProcesses
        if (runningAppProcessInfos != null) {
            for (appProcess in mActivityManager.runningAppProcesses) {
                if (appProcess.pid == pid) {
                    processName = appProcess.processName
                    break
                }
            }
            val packageName = app.packageName
            if (processName == packageName) {
                return true
            }
        }
        return false
    }

    @SuppressLint("WrongConstant")
    fun registerReceiver(context: Context, receiver: BroadcastReceiver, intentFilter: IntentFilter) {
        if (Build.VERSION.SDK_INT >= 33) {
            //这里兼容安卓14 RECEIVER_EXPORTED
            context.registerReceiver(receiver, intentFilter, 0x2)
        } else {
            context.registerReceiver(receiver, intentFilter)
        }
    }

    fun loge(str: String) {
        if (config.isDebug) {
            Log.e("KeepLive", str)
        }
    }

    fun requestAutoStartPermission(context: Context) {
        val manufacturer = Build.MANUFACTURER.lowercase(Locale.getDefault())
        if (manufacturer.contains("huawei")) {
            gotoHuaweiAutoStartSetting(context)
        } else if (manufacturer.contains("xiaomi")) {
            gotoXiaomiAutoStartSetting(context)
        } else if (manufacturer.contains("oppo")) {
            gotoOppoAutoStartSetting(context)
        } else if (manufacturer.contains("vivo")) {
            gotoVivoAutoStartSetting(context)
        }
        // 其他厂商的引导逻辑
    }

    fun gotoHuaweiAutoStartSetting(context: Context) {
        val intent = Intent()
        intent.setComponent(ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"))
        context.startActivity(intent)
    }

    fun gotoXiaomiAutoStartSetting(context: Context) {
        val intent = Intent("miui.intent.action.APP_PERM_EDITOR")
        intent.setPackage("com.miui.securitycenter")
        intent.putExtra("extra_pkgname", context.packageName)
        context.startActivity(intent)
    }

    fun gotoOppoAutoStartSetting(context: Context) {
        val intent = Intent()
        intent.setComponent(ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"))
        context.startActivity(intent)
    }

    fun gotoVivoAutoStartSetting(context: Context) {
        val intent = Intent()
        intent.setComponent(ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"))
        context.startActivity(intent)
    }
}